package com.safframework.androidserver.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.acheng.ws.client.AbstractClient
import com.acheng.ws.client.listener.WebSocketListener
import io.netty.channel.Channel
import io.netty.handler.codec.http.FullHttpResponse
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors

class WsClientService : Service(), WebSocketListener {

    val wsUrl = "ws://cn.rtrans.yunjivip.cn/rasr/?aaa=111"

    val TAG = this.javaClass.simpleName
    val countDown = CountDownLatch(1)

    private val threadExecutor = Executors.newSingleThreadExecutor()

    override fun onCreate() {
        super.onCreate()

        onOpen()

    }

    private fun onOpen() {
        val abstractClient = object : AbstractClient(wsUrl, this) {}
        abstractClient.addHeader("aaa", "bbb")
        abstractClient.init()
        countDown.await()
        Log.e(TAG, "onOpen: 下面完成")
        threadExecutor.submit {
            while (true) {
                Log.e(TAG, "打印ping时间: ${abstractClient.ping()}")
                Thread.sleep(1000)
            }
        }

    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }


    override fun onDestroy() {

        super.onDestroy()
    }

    override fun onOpen(webSocket: Channel?, response: FullHttpResponse?) {
        Log.e(TAG, "onOpen: 打开了")
        countDown.countDown()
    }

    override fun onFailure(webSocket: Channel?, t: Throwable?, response: FullHttpResponse?) {
        Log.e(TAG, "onFailure: 扑街", t)
    }

    override fun onFailure(webSocket: Channel?, t: Throwable?) {
        Log.e(TAG, "onFailure: 扑街", t)
    }

    override fun onClosing(webSocket: Channel?, code: Int, reason: String?) {
        Log.e(TAG, "onClosing: 关闭")
    }

    override fun onMessage(webSocket: Channel?, text: String?) {
        Log.e(TAG, String.format("onMessage: 收到消息=$text"))
    }

    override fun onMessage(webSocket: Channel?, bytes: ByteArray?) {
        Log.e(TAG, String.format("onMessage: 收到二进制消息长度=${bytes?.size}"))
    }

    override fun onClosed(webSocket: Channel?, code: Int, reason: String?) {
        Log.e(TAG, "onClosed: 关闭，code=$code，原因=$reason")
    }


}